<template>
  <div class="content">
    <div class="tab_box">
      <u-tabs
        @change="changeTab"
        :list="list1"
        :activeStyle="{
          color: '#23AC39',
          fontSize: '30rpx',
          fontWeight: 500,
        }"
        :inactiveStyle="{
          color: '#999999',
          fontSize: '30rpx',
          fontWeight: 500,
        }"
        lineColor="#23AC39"
      ></u-tabs>
    </div>

    <!-- 套餐 -->
    <block v-if="!tabIndex">
      <div class="list_box">
        <div class="box">
          <div
            @click="changeTc(item, index)"
            class="box2"
            v-for="(item, index) in list"
            :key="index"
          >
            <div class="msg">
              <p class="t_t">发布条数（{{ item.number }}条）</p>
              <p class="text">{{ item.introduction }}</p>
            </div>
            <div class="right">
              <p class="price">{{ item.price }}元</p>
            </div>
            <p class="on" v-if="index == tcIndex">
              <img src="/static/gou.png" alt="" />
              <span>
                <u-icon name="checkbox-mark" color="#fff" size="20"></u-icon>
              </span>
            </p>
          </div>
        </div>
        <div class="box2">
          <div class="msg">
            <p class="t_t">免费获取发布数条</p>
            <p class="text">*每邀请1人 新增1条发布条数</p>
          </div>
          <div class="right">
            <button class="an" open-type="share">去分享</button>
          </div>
        </div>
      </div>

      <!-- 安卓设备 -->

      <block v-if="currentPrice === 0">
        <div class="totle_price">
          <p>小计</p>
          <p class="price" v-if="tabMsg.price">¥{{ tabMsg.price }}</p>
        </div>
        <div class="play_box">
          <p class="title">支付方式</p>
          <div class="radio-group-container">
            <radio-group v-model="selectedOption" @change="changePlayType">
              <label
                class="radio-label"
                v-for="option in options"
                :key="option.value"
              >
                <div class="text">
                  <img :src="option.icon" alt="" />
                  {{ option.text }}
                  <span v-if="option.isYe">(账户余额0.00元)</span>
                </div>
                <!-- <radio v-model="option.value" /> -->
                <img class="gx" src="/static/xz.png" alt="" />
              </label>
            </radio-group>
          </div>
          <u-button
            :disabled="isDisable"
            loadingMode="circle"
            :loading="isDisable"
            loadingText="领取中..."
            type="primary"
            text="立即领取"
            @click="submitplay"
          >
          </u-button>
          <p class="play_jl" @click="toGmList">我的购买记录</p>
        </div>
      </block>

      <block v-else-if="isIos">
        <div class="totle_price">
          <p>小计</p>
          <p class="price" v-if="tabMsg.price">¥{{ tabMsg.price }}</p>
        </div>
        <div class="play_box">
          <p class="title">支付方式</p>
          <div class="radio-group-container">
            <radio-group v-model="selectedOption" @change="changePlayType">
              <label
                class="radio-label"
                v-for="option in options"
                :key="option.value"
              >
                <div class="text">
                  <img :src="option.icon" alt="" />
                  {{ option.text }}
                  <span v-if="option.isYe">(账户余额0.00元)</span>
                </div>
                <!-- <radio v-model="option.value" /> -->
                <img class="gx" src="/static/xz.png" alt="" />
              </label>
            </radio-group>
          </div>
          <u-button
            :disabled="isDisable"
            loadingMode="circle"
            :loading="isDisable"
            loadingText="支付中..."
            type="primary"
            text="立即支付"
            @click="submitplay"
          >
          </u-button>
          <p class="play_jl" @click="toGmList">我的购买记录</p>
        </div>
      </block>

      <!-- ios设备 -->
      <div class="ios_play" v-else-if="!isIos && currentPrice > 0">
        <div class="ios">
          <p class="text">ios用户暂不可再小程序内开通</p>
          <button class="b4" style="height: 40px;" open-type="contact" 
              send-message-title="诸信接单"
              send-message-path="/pages/my/main"
              show-message-card="true"
              > 点此解决（回复任意文字即可） </button>
        </div>
      </div>
    </block>

    <!-- 转赠 -->
    <block v-else>
      <div class="zz_box">
        <div class="head_bj">
          <img class="bj" src="https://zxsd-oss-img.oss-cn-chengdu.aliyuncs.com/d1ccbc07b9d8a50faab069113df1f224d90d85bff1ded0d30f430fe751ce9e91.jpg" alt="" />
          <div class="zz_tab">
            <div>
              <p class="num">{{ zzMsg.notUsedCount }}</p>
              <p class="text">可发布条数</p>
            </div>
            <div>
              <p class="num">{{ zzMsg.giveCount }}</p>
              <p class="text">可转赠条数<img src="/static/wh.png" alt="" /></p>
            </div>
          </div>
        </div>
        <div class="nr_box">
          <div class="box">
            <p class="title">转赠数量</p>
            <div class="cz">
              <p @click="jian">-</p>
              <p class="num">{{ num }}</p>
              <p @click="add">+</p>
            </div>
          </div>
          <div class="box" style="margin-bottom: 120rpx">
            <p class="title">受赠人ID号</p>
            <input
              type="text"
              placeholder="请输入"
              v-model="transfer_user_id"
            />
          </div>

          <u-button
            :disabled="isDisable"
            loadingMode="circle"
            :loading="isDisable"
            loadingText="转赠中..."
            type="primary"
            text="确认转赠"
            @click="submit"
          >
          </u-button>
          <p class="play_jl" @click="toZzList">我的转赠记录</p>
        </div>
      </div>
    </block>

  </div>
</template>

<script>
import { mapState } from "vuex"
import api from "@/api"
import { Debounce } from "@/utils/utils.js"
import Config from "@/config/index.js"
export default {
  data() {
    return {
      tabIndex: 0,
      list1: [
        {
          name: "套餐",
        },
        {
          name: "转增",
        },
      ],
      selectedOption: "1", // 用于v-model绑定，存储选中的值
      options: [
        {
          isYe: false,
          icon: "/static/wx_play.png",
          value: "1",
          text: "微信支付",
        },
        // { isYe:true,icon:'/static/ye_play.png',value: '2', text: '余额支付' },
        // 更多选项...
      ],
      isDisable: false, // 提交
      tcIndex: 0,
      list: [],

      num: 1,
      transfer_user_id: "",
      zzMsg: {},
      tabMsg: {},
      shareUserId: "",
      isIos: false,
    }
  },
  computed: {
    ...mapState({
      userId: (state) => state.user.userId,
      token: (state) => state.user.token,
    }),
    currentPrice() {
      return this.tabMsg.price * 100
    },
  },
  methods: {
    clickTs() {
      this.$toast("此功能即将上线！")
    },

    checkPlatform() {
      const systemInfo = uni.getSystemInfoSync()
      const platform = systemInfo.platform // 获取平台信息

      api.user.get_IOS_enable().then((res) => {
        if (res.code == 200) {
          if (platform === "ios" && res.data) {
            console.log("当前设备是 iOS, 微信支付已开启")
            this.isIos = true
          } else if (platform === "ios" && !res.data) {
            console.log("当前设备是 iOS, 微信支付未开启")
            this.isIos = false
          } else {
            console.log("当前设备不是 iOS")
            this.isIos = true
          }
        } 
      })
    },

    // 选择支付方式
    changePlayType(e) {
      console.log(e)
    },

    // 提交转赠记录
    submit() {
      if (!this.token) {
        uni.navigateTo({
          url: `/pages/authorization/index?shareUserId=${this.shareUserId}`,
        })
        return
      }
      if (!this.transfer_user_id) {
        this.$toast("请输入受赠人ID~")
        return
      }
      this.$showLoading("转赠中...")
      this.isDisable = true
      let data = {
        transfer_user_id: this.transfer_user_id,
        num: this.num,
      }
      api.user.transfer(data).then((res) => {
        if (res.code == 200) {
          uni.hideLoading()
          this.isDisable = false
          this.transfer_user_id = ""
          this.num = 1
          uni.navigateTo({
            url: "/pages/taocan/zzList/index",
          })
        } else {
          uni.hideLoading()
          this.isDisable = false
          this.$toast(res.msg)
        }
      })
    },

    // 获取可发送条数
    getFbNum() {
      api.user
        .package_get({
          userId: this.userId,
        })
        .then((res) => {
          if (res.code == 200) {
            this.zzMsg = res.data
            console.log(this.zzMsg)
          }
        })
    },

    add() {
      if (this.num >= this.zzMsg.giveCount) {
        this.$toast("不能大于转正数~")
        return
      }
      this.num++
    },

    jian() {
      if (this.num <= 1) {
        return
      }
      this.num--
    },

    changeTc(item, index) {
      console.log(item, index)
      this.tabMsg = item
      this.tcIndex = index
    },

    changeTab(e) {
      console.log(e)
      this.tabIndex = e.index
    },

    toZzList() {
      if (!this.token) {
        uni.navigateTo({
          url: `/pages/authorization/index?shareUserId=${this.shareUserId}`,
        })
        return
      }
      uni.navigateTo({
        url: "/pages/taocan/zzList/index",
      })
    },

    toGmList() {
      if (!this.token) {
        uni.navigateTo({
          url: `/pages/authorization/index?shareUserId=${this.shareUserId}`,
        })
        return
      }
      uni.navigateTo({
        url: "/pages/taocan/gmList/index",
      })
    },

    // 获取列表
    getList() {
      api.user.list_by_ids().then((res) => {
        if (res.code == 200) {
          res.data.map((item) => {
            item.price = (item.price / 100).toFixed(2)
          })
          this.list = res.data
          this.tabMsg = res.data[0]
        }
      })
    },
    //支付金额为0，走记账流程，直接领取条数给用户
    async getFreeCount() {
      this.isDisable = true
      this.$showLoading("领取中...")
      setTimeout(async () => {
        const data = {
          spuId: this.tabMsg.id,
          count: 1,
          num: this.tabMsg.number,
        }
        await api.user.modify_count(data).then((res) => {
          if (res.code == 200) {
            this.$toast("领取成功～")
            setTimeout(() => {
              uni.hideLoading()
              this.isDisable = false
              uni.navigateTo({
                url: "/pages/taocan/gmList/index",
              })
            }, 1500);
          } else {
            this.$toast("购买免费领取失败，请联系管理员")
          }
        })
      }, 1500);
    },
    // 创建订单-发起支付
    async submitplay() {
      if (!this.token) {
        uni.navigateTo({
          url: `/pages/authorization/index?shareUserId=${this.shareUserId}`,
        })
        return
      }

      if (this.currentPrice < 1) {
        this.getFreeCount()
        return
      }

      this.$showLoading("支付中...")
      this.isDisable = true
      let data = {
        spuId: this.tabMsg.id,
        count: 1,
      }
      let payOrderId = ""
      await api.user.order_create(data).then((res) => {
        if (res.code == 200) {
          payOrderId = res.data.payOrderId
        } else {
          uni.hideLoading()
          this.isDisable = false
          this.$toast(res.msg)
        }
      })
      if (payOrderId) {
        let canshu = {
          id: payOrderId,
          channelCode: "wx_lite",
        }
        await api.user.pay_order(canshu).then((res) => {
          if (res.code == 200) {
            let payObj = JSON.parse(res.data.displayContent)
            console.log(payObj)
            uni.requestPayment({
              timeStamp: payObj.timeStamp,
              nonceStr: payObj.nonceStr,
              package: payObj.packageValue,
              signType: payObj.signType,
              paySign: payObj.paySign,
              success: (succ) => {
                console.log(succ)
                if (succ.errMsg === "requestPayment:ok") {
                  uni.hideLoading()
                  this.isDisable = false
                  this.$toast("支付成功～")
                  uni.navigateTo({
                    url: "/pages/taocan/gmList/index",
                  })
                }
              },
              fail: (err) => {
                uni.hideLoading()
                this.isDisable = false
                this.$toast("支付失败！")
              },
            })
          } else {
            uni.hideLoading()
            this.isDisable = false
            this.$toast(res.msg)
          }
        })
      }
    },
  },
  onLoad(options) {
    this.selectedOption = "1"
    this.getList()

    if (options.shareUserId) {
      this.shareUserId = options.shareUserId
    }
    // api.user.get_enable_code_list({appId:9}).then(res=>{

    // })
  },
  onShow() {
    this.getFbNum()

    this.checkPlatform()
  },
  onShareAppMessage() {
    return {
      title: "免费用万人接单群",
      path: `/pages/taocan/index?shareUserId=${this.userId}`,
    }
  },
}
</script>

<style lang="scss" scoped>
.content {
  min-height: 100vh;
  background: #f7f7f7;
  padding-bottom: 30rpx;

  .tab_box {
    background: #fff;

    /deep/ .u-tabs__wrapper__nav__item {
      // justify-content: space-around;
      padding: 0 21%;
    }
  }

  .list_box {
    padding: 30rpx;

    .box2 {
      padding: 0 30rpx;
      height: 87px;
      border-radius: 5px;
      background: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 22rpx;
      position: relative;

      .on {
        position: absolute;
        top: 0;
        right: 0;

        img {
          width: 70rpx;
          height: 70rpx;
        }

        span {
          position: absolute;
          top: 4rpx;
          right: 0;
        }
      }

      .msg {
        .t_t {
          font-size: 28rpx;
          font-weight: bold;
          color: #3d3d3d;
        }

        .text {
          font-size: 28rpx;
          color: #999999;
          margin-top: 16rpx;
        }
      }

      .right {
        .price {
          color: #ff5218;
          font-size: 28rpx;
          font-weight: bold;
          text-align: right;
        }

        .oldPrice {
          color: #999999;
          font-size: 28rpx;
          text-decoration: line-through;
        }

        .label {
          width: 180rpx;
          height: 42rpx;
          line-height: 42rpx;
          background: #cbe9e5;
          font-size: 28rpx;
          color: #ff5218;
          padding-left: 10rpx;
        }

        .an {
          width: 67px;
          height: 62rpx;
          line-height: 62rpx;
          border-radius: 100rpx;
          background: #23ac39;
          box-sizing: border-box;
          font-size: 28rpx;
          color: #ffffff;
          padding: 0;

          &::after {
            border: none;
          }
        }
      }
    }
  }

  .totle_price {
    margin: 0 39rpx;
    border-bottom: 1px solid #d8d8d8;
    padding-bottom: 18rpx;
    display: flex;
    justify-content: space-between;
    font-size: 32rpx;
    color: #333;

    .price {
      font-weight: bold;
    }
  }

  .play_box {
    margin: 24rpx 30rpx;

    .title {
      font-size: 32rpx;
      color: #333;
      margin-bottom: 30rpx;
    }

    .radio-group-container {
      display: flex;
      flex-direction: column;
      margin-bottom: 30rpx;

      .radio-label {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
        /* 根据需要调整间距 */
      }

      .text {
        font-size: 32rpx;
        color: #333;
        display: flex;
        align-items: center;

        img {
          width: 40rpx;
          height: 40rpx;
          margin-right: 10rpx;
        }

        span {
          color: #999;
          font-size: 24rpx;
        }
      }

      .gx {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  /deep/ .u-button {
    height: 96rpx;
    line-height: 96rpx;
    border-radius: 100rpx;
    background: #23ac39;
    font-size: 32rpx;
    text-align: center;
    font-weight: 500;
    color: #fff;
    border: none;
  }

  .play_jl {
    text-align: center;
    color: #999999;
    font-size: 32rpx;
    font-weight: 500;
    margin-top: 22rpx;
  }

  .zz_box {
    .head_bj {
      position: relative;

      .bj {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 298rpx;
      }

      .zz_tab {
        height: 298rpx;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-around;
        text-align: center;
        color: #fff;

        .num {
          font-size: 40rpx;
          font-weight: 500;
        }

        .text {
          font-size: 36rpx;
          margin-top: 16rpx;
          font-weight: 500;
          display: flex;
          align-items: center;

          img {
            width: 40rpx;
            height: 40rpx;
            margin-left: 6rpx;
          }
        }
      }
    }

    .nr_box {
      margin: 0 30rpx;

      .box {
        border-bottom: 1px solid #d8d8d8;
        height: 100rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .title {
          font-size: 28rpx;
          color: #3d3d3d;
        }

        .cz {
          display: flex;
          align-items: center;
          color: #333;
          font-size: 28rpx;

          p {
            padding: 0 16rpx;
          }
        }

        input {
          text-align: right;
          font-size: 28rpx;
        }
      }
    }
  }

  .ios_play {
    background: #fff;
    padding: 20rpx;
    margin: 30rpx;
    border-radius: 10rpx;
    margin-top: 0;

    .ios {
      background: #f7f7f7;
      border-radius: 10rpx;
      padding: 20rpx;
      text-align: center;

      .text {
        color: #23ac39;
        font-size: 30rpx;
      }

      .an {
        border-radius: 10rpx;
        padding: 8rpx 0;
        background: #fff;
        color: #23ac39;
        width: 170rpx;
        font-size: 32rpx;
        margin: 20rpx auto 0 auto;
      }
      .b4{
        width: 280px ;
      // padding: 20px 0;
        text-align: center;
        line-height: 40px;
        background: #23ac39;
        border: 1px solid transparent;
        color: #fff;
        border-radius: 5px;
        margin-top: 17px;
        text-align: center;
        font-size:30rpx;
      }
    }
  }
}
</style>
